package com.fiblue.soexcel.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson2.JSON;
import com.fiblue.soexcel.pojo.FamilyPojo;
import com.fiblue.soexcel.pojo.MemberPojo;
import com.fiblue.soexcel.pojo.PeopleData;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class PeopleListener implements ReadListener<PeopleData> {


    /**
     * 缓存的数据
     */
    private List<PeopleData> cachedDataList=new ArrayList<>();

    public PeopleListener() {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
    }
    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(PeopleData data, AnalysisContext context) {
        String area= data.getArea();
        if (area.contains("龙腰村")){
            cachedDataList.add(data);
            //System.out.println("解析到一条数据:  "+JSON.toJSONString(data));
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 解析数据
        List<FamilyPojo> familyPojoList=parseData();
        String path="D:\\hacker\\code\\soexcel\\temp\\2024年南丹县城乡低保家庭情况核查表.xlsx";
/*        try {
            buildTemplateFile(path,familyPojoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        System.out.println("长度：  "+familyPojoList.size());
       // FamilyPojo familyPojo=familyPojoList.get(0);
        try {
            fillData(familyPojoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void buildTemplateFile(String path,List<FamilyPojo> familyPojoList) throws IOException {
        // 加载模板文件
        File file=new File(path);
        InputStream templateStream = new FileInputStream(file);
        Workbook workbook = WorkbookFactory.create(templateStream);
        // 设置模板sheet数量, 需要复制promptMap.size()-1 次工作表2
        for(int i = 0; i < familyPojoList.size(); i++) {
            Sheet newSheet = workbook.cloneSheet(0);
            workbook.setSheetName(workbook.getSheetIndex(newSheet),familyPojoList.get(i).getOwner());
        }
        templateStream.close();
        FileOutputStream fileOutputStream=new FileOutputStream(file);
        workbook.write(fileOutputStream);
        // 原文件流后续已不使用，此处关闭
        fileOutputStream.close();
        }

     public void fillData(List<FamilyPojo> familyPojoList) throws IOException {
         String fileName = "D:\\hacker\\code\\soexcel\\temp\\2024年南丹县城乡低保家庭情况核查表B.xlsx";
         String templateFileName = "D:\\hacker\\code\\soexcel\\temp\\2024年南丹县城乡低保家庭情况核查表.xlsx";
         try (ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build()) {
         for(int i = 0; i < familyPojoList.size(); i++) {
             FamilyPojo familyPojo=familyPojoList.get(i);
             List<MemberPojo> memberPojoList=familyPojo.getMembers();
             WriteSheet writeSheet = EasyExcel.writerSheet(i,familyPojo.getOwner()).build();
             // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
             // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
             // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
             // 如果数据量大 list不是最后一行 参照下一个
             FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
             excelWriter.fill(familyPojo, fillConfig, writeSheet);
             excelWriter.fill(memberPojoList, fillConfig, writeSheet);
         }

         }
     }
    /**
     * 加上存储数据库
     */
    private List<FamilyPojo> parseData() {
        //demoDAO.save(cachedDataList);
        List<FamilyPojo> familyPojoList=new ArrayList<>();
        for (int i = 0; i < cachedDataList.size(); i++) {
            PeopleData peopleData=cachedDataList.get(i);
            if(peopleData.getRelationship().equals("本人")){
                FamilyPojo familyPojo=new FamilyPojo();
                String ownerIDCardNo=peopleData.getOwnerIDCardNo();
                familyPojo.setOwnerIDCardNo(peopleData.getOwnerIDCardNo());
                familyPojo.setOwner(peopleData.getOwnerName());
                familyPojo.setOwnerSex(peopleData.getSex());
                familyPojo.setOwnerNation(peopleData.getNation());
                familyPojo.setNumber(peopleData.getNumber());
                familyPojo.setAddress(peopleData.getAddress());
                familyPojo.setPhoneNo(peopleData.getPhoneNo());
                List<MemberPojo> memberPojoList=new ArrayList<>();
                for (int j = 0; j < cachedDataList.size(); j++) {
                    PeopleData peopleData2=cachedDataList.get(j);
                    MemberPojo memberPojo=new MemberPojo();
                    if(ownerIDCardNo.equals(peopleData2.getOwnerIDCardNo())){
                        String relationship = "";
                        memberPojo.setIDCardNo(peopleData2.getIDCardNo());
                        memberPojo.setAge(peopleData2.getAge());
                        memberPojo.setName(peopleData2.getName());
                        if(peopleData2.getRelationship().equals("子")){
                            relationship="儿"+peopleData2.getRelationship();
                        }
                        else if(peopleData2.getRelationship().equals("女")){
                            relationship=peopleData2.getRelationship()+"儿";
                        }
                        else {
                            relationship=peopleData2.getRelationship();
                        }
                        memberPojo.setRelationship(relationship);
                        memberPojo.setSex(peopleData2.getSex());
                        memberPojo.setNation(peopleData2.getNation());
                        memberPojoList.add(memberPojo);
                    }

                }
                familyPojo.setMembers(memberPojoList);
                familyPojoList.add(familyPojo);
            }
        }
        return familyPojoList;
    }
}
